package com.internship.javawebinternship.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.internship.javawebinternship.myUtils.UnicodeUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.net.URLEncoder;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.text.StringEscapeUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
public class GetCovid19Info {
    @PostMapping("/getCovid19Info")
    public Object covid19(@RequestBody String frontEnd) {
        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
        String city = receiveJSON.getString("city");

        String url;
        if (city == null || city.equals(""))
            url = "https://opendata.baidu.com/data/inner?resource_id=5653&query=%E5%9B%BD%E5%86%85%E7%96%AB%E6%83%85&&tn=wisexmlnew&alr=1&is_opendata=1";
        else {
            city = city + "疫情";
            city = URLEncoder.encode(city, StandardCharsets.UTF_8);
            url = "https://opendata.baidu.com/data/inner?resource_id=5653&query=" + city + "&tn=wisexmlnew&alr=1&is_opendata=1";
        }

        String result = "";
        try {
            Connection.Response document = Jsoup.connect(url).timeout(10000).userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56").ignoreContentType(true).execute();
            Document temp = document.parse();

            //去除HTTP响应中不需要的数据
            String main = temp.toString().split("<html>\n <head></head>\n <body>\n ")[1].split("\n </body>\n</html>")[0];

            //将JSON数据中的Unicode字符转换为正常字符
            main = UnicodeUtil.toString(main);

            //将JSON数据最后的“}”去掉，准备向其中添加数据
            main = main.substring(0, main.length() - 1);

            //去除返回结果中的乱码
            main = main.replaceAll("\"url_feature_channel\".*}],", "}],");
            main = main.replaceAll("\"query_trans_feature\".*,", "");
            main = main.replaceAll("\"disp_data_query_ex\".*,", "");
            main = main.replaceAll("\"queryDispInfo\".*", "");

            if (city == null || city.equals("")) {
                //获得JSON数据中的JSON数据
                String trend = extractInfoFromJSON(main, "trend");
                String resumeIn = extractInfoFromJSON(main, "resumeIn");
                String resumeOut = extractInfoFromJSON(main, "resumeOut");

                //去除原JSON中，上一步已经获得的数据
                main = main.replaceAll(",\"trend\".*}]\",", ",");
                main = main.replaceAll(",\"resumeIn\".*}]\",", ",");
                main = main.replaceAll(",\"resumeOut\".*}]\",", ",");

                //将以上数据进行拼接，并补齐缺失的反括号
                result = main + trend + resumeIn + resumeOut + "}}";
                result = result.replaceAll(",,", ",");

            } else {
                //获得JSON数据中的JSON数据
                String trend = extractInfoFromJSON(main, "trend");

                if (main.contains("dangerousAreas")) {//国内城市有高风险地区的数据
                    String dangerousAreas = main.split("\"dangerousAreas\":")[1].split("}\",")[0];
                    dangerousAreas = ",\"dangerousAreas" + "\": " + dangerousAreas + "}\"";
                    dangerousAreas = StringEscapeUtils.unescapeJava(dangerousAreas);
                    dangerousAreas = dangerousAreas.replaceAll("\"\\{", "\\{");
                    dangerousAreas = dangerousAreas.replaceAll("\":\\{", ":\\{");
                    dangerousAreas = dangerousAreas.substring(0, dangerousAreas.length() - 1);

                    //去除原JSON中，上一步已经获得的数据
                    main = main.replaceAll(",\"trend\".*}]\",", "");
                    main = main.replaceAll("\"dangerousAreas\".*}\",", "");

                    //去除JSON中不需要的数据
                    main = main.replaceAll(",\"resume\".*,", ",");

                    //将以上数据进行拼接，并补齐缺失的反括号
                    result = main + trend + dangerousAreas + "}}}}]}";
                    result = result.replaceAll(",,", ",");

                } else {//国外城市没有高风险地区的数据
                    main = main.replaceAll(",\"trend\".*,", "");
                    main = main.replaceAll(",\"resume\".*,", ",");
                    result = main + trend + "}}}}]}";
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ArrayIndexOutOfBoundsException e) {
            Map<String, Object> result1 = new HashMap<>();
            result1.put("ResultCode", "ERROR");
            JSONObject object = new JSONObject(result1);//使用JSONObject，将map转化为json数据
            return object;//返回json数据给前端
        }
        JSONObject object = JSON.parseObject(result);//使用JSONObject，将结果字符串转化为json数据
        return object;//返回json数据给前端
    }

    //从原JSON中取出需要的数据，做对应处理，保存
    private String extractInfoFromJSON(String main, String name) {
        String need = main.split("\"" + name + "\":")[1].split("}]\",")[0];
        need = ",\"" + name + "\": " + need + "}]\"";
        need = StringEscapeUtils.unescapeJava(need);//调用方法，将字符串中的转义字符删去，使得JSON可以正常解析
        need = need.replaceAll("\"\\[\\{", "\\[\\{");
        need = need.replaceAll("\":\\[\\{", ":\\[\\{");
        need = need.substring(0, need.length() - 1);

        return need;
    }
}
